<template>
  <div>
    <div id="app">
      <div class="list">
        <div class="item" v-for="(item, index) in products" :key="index">
          <img :src="imgUrl" alt="" />
          <div class="info">
            <div class="name">{{ item.name }}</div>
            <div class="price">{{ item.price }}元</div>
            <div class="number">
              <!-- <button @click="reduce(index)">-</button> -->
              <button @click="item.number == 0 ? 0 : item.number--">-</button>
              <div class="count">
                {{ item.number }}
              </div>
              <button @click="item.number++">+</button>
            </div>
          </div>
        </div>
      </div>
      <div class="totalPrice">总价格: {{ totalPrice }}元</div>
    </div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      imgUrl:
        "https://cdn.cnbj1.fds.api.mi-img.com/mi-mall/8729282b199b3ec51e31c1b6b15f3f93.jpg?thumb=1&w=250&h=250&f=webp&q=90",
      products: [
        {
          name: "小米11",
          price: 3000,
          number: 1,
        },
        {
          name: "荣耀6",
          price: 1300,
          number: 1,
        },
        {
          name: "苹果12",
          price: 6000,
          number: 1,
        },
      ],
      // totalPrice: 0,
    };
  },
  methods: {
    // add(index) {
    //   this.products[index].number++;
    //   console.log(1);
    // },
    reduce(index) {
      if (this.products[index].number <= 0) {
        return;
      }
      this.products[index].number--;
    },
  },
  computed: {
    // totalPrice() {
    //   let totalPrice = 0;
    //   let len = this.products.length;
    //   for (let i = 0; i < len; i++) {
    //     totalPrice += this.products[i].price * this.products[i].number;
    //   }
    //   return totalPrice;
    // },

    // totalPrice: function () {
    //   var totalPrice = 0;
    //   var len = this.products.length;
    //   for (var i = 0; i < len; i++) {
    //     totalPrice += this.products[i].price * this.products[i].number;
    //   }
    //   return totalPrice;
    // },
    totalPrice() {
      let total = 0;
      this.products.forEach((item) => {
        total += item.price * item.number;
      });
      return total;
    },
  },
};
</script>

<style lang="less" scoped>
#app {
  background: #eee;
  width: 380px;
  height: 640px;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
}
.item {
  display: flex;
  align-items: center;
  border: 1px solid #e4e4e4;
  background-color: white;
  box-sizing: border-box;
  width: 380px;
  justify-content: space-between;
  margin: 5px 0;
}
.info {
  flex: 1;
  display: flex;
  font-size: 24px;
  justify-content: space-around;
  align-items: center;
}
img {
  width: 70px;
  height: 70px;
}
.number {
  display: flex;
  align-items: center;
}
.count {
  padding: 10px;
}
.totalPrice {
  font-size: 26px;
  padding: 24px;
}
</style>

